package org.csu.mypetstore.Controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.csu.mypetstore.checkcode.EncryptUtil;
import org.csu.mypetstore.checkcode.RandomValidateCodeUtil;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CategortService;
import org.csu.mypetstore.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.jws.WebParam;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.rmi.server.ExportException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/account")
@SessionAttributes("account")
public class AccountController {

    @Autowired
    private AccountService accountService;
    @Autowired
    LogService logService;
    @Autowired
    CategortService categortService;

    @PostMapping("/login")
    public String login(Model model, HttpServletRequest req) {
        HttpSession session = req.getSession();
        Account account;
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        password = EncryptUtil.md5(password);

        if (username == null) {
            return "/account/SignonForm";
        } else {
            if (accountService.getAccount(username, password) == null) {
                model.addAttribute("msg", "Failed! Your uername or password is wrong");
                return "/common/Error";
            } else {
                account = accountService.getAccount(username, password);
                model.addAttribute("account", account);
                session.setAttribute("account", account);
                List<Category> categoryList =  categortService.getCategoryList();
                List<Product> productList = categortService.getallproduct();
                model.addAttribute("account",account);
                model.addAttribute("categoryList",categoryList);
                model.addAttribute("productList",productList);
                return "/catalog/test";
            }
        }
    }

    @GetMapping("/myaccount")
    public String myaccount(Model model, HttpServletRequest req) {
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        String username = account.getUsername();
        String password = account.getPassword();
        if (account == null) {
            return "/account/SignonForm";
        } else {
            account = accountService.getAccount(username, password);
            model.addAttribute("account", account);
            return "/account/EditAccountForm";
        }
    }

    @GetMapping("/viewlogin")
    public String viewlogin() {
        return "/account/SignonForm";
    }


    @GetMapping("/signout")
    public String singout(Model model, HttpServletRequest req) {
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        if (account != null) {
            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + " 退出账号";
            logService.insertLogInfo(account.getUsername(), logInfo);
            account = null;
            List<Category>categoryList =  categortService.getCategoryList();
            List<Product>productList = categortService.getallproduct();
            model.addAttribute("account",account);
            model.addAttribute("categoryList",categoryList);
            model.addAttribute("productList",productList);
            return "/catalog/test";
        } else {
            return "/common/Error";
        }

    }

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @RequestMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @RequestMapping("/ViewIncludeAccountFields")
    public String ViewIncludeAccountFields(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        password = EncryptUtil.md5(password);
        Account account = accountService.getAccount(username, password);
        //获得输入的验证码值
        String captchaId = (String) req.getSession().getAttribute("vrifyCode");
        String parameter = req.getParameter("vCode");

        /*获取图片的值*/

        boolean isSame = false;
        if (captchaId.equals(parameter)) {
            isSame = true;
        }
        if (accountService.getAccount(username, password) == null) {
            return "/account/SignonForm";
        } else {
            if (isSame) {
                model.addAttribute("account", account);
                if (account != null) {
                    String logInfo = " 用户登录";
                    logService.insertLogInfo(account.getUsername(), logInfo);
                }
                List<Category>categoryList =  categortService.getCategoryList();
                List<Product>productList = categortService.getallproduct();
                List<LatestProduct> latestProducts = categortService.getlatestproduct();
                model.addAttribute("account",account);
                model.addAttribute("categoryList",categoryList);
                model.addAttribute("productList",productList);
                model.addAttribute("latestProducts",latestProducts);
                session.setAttribute("account", account);
                session.setAttribute("latestProducts",latestProducts);
                return "/catalog/test";
            } else {
                String logInfo = " 注册账号，验证码错误";
                logService.insertLogInfo(account.getUsername(), logInfo);
                //验证码输入错误后刷新界面，重新生成验证码
                return "/account/SignonForm";
            }
        }
    }

    @RequestMapping("/ViewEditInformationFormServlet")
    public String ViewEditInformationFormServlet(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        String username = req.getParameter("username");
        if((account==null&&username!=null)||(account!=null&&username!=null)){//处理从后台来的account为null的现象
            account = accountService.getAccount(username);
            model.addAttribute("account", account);
            return "/account/EditAccountForm";
        }else if(account!=null&&username==null){
            model.addAttribute("account", account);
            return "/account/EditAccountForm";
        }
        else {
            return "/account/SignonForm";
        }

    }
    @RequestMapping("/ViewIncludeAccountFieldsbyphone")
    public String ViewIncludeAccountFieldsbyphone(HttpServletRequest req,Model model){
        String verifyCode = (String) req.getSession().getAttribute("verifyCode");
        String inputverifyCode = req.getParameter("inputverifyCode");
        String phonenumber = req.getParameter("phonenumber");
        HttpSession session = req.getSession();
        boolean flag = false;
        if(inputverifyCode.equals(verifyCode))
            flag=true;
        if(flag){
            Account account = accountService.getAccount(accountService.getAccountbyphone(phonenumber));
            List<Category>categoryList =  categortService.getCategoryList();
            List<Product>productList = categortService.getallproduct();
            List<LatestProduct> latestProducts = categortService.getlatestproduct();
            model.addAttribute("latestProducts",latestProducts);
            session.setAttribute("latestProducts",latestProducts);
            model.addAttribute("account",account);
            model.addAttribute("categoryList",categoryList);
            model.addAttribute("productList",productList);
            session.setAttribute("account", account);
            return "/catalog/test";
        }else {
            return "/account/SignonForm";
        }
    }
    @RequestMapping("/ViewNewAccount")
    public String ViewMyOrderServlet() {
        return "/account/together";
    }

    @RequestMapping("/UsernameIsExist")
    public void UsernameIsExist(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        response.setContentType("text/xml");
        try {
            PrintWriter out = response.getWriter();
            if (accountService.getAccount(username) != null) {
                out.println("<msg>Exist</msg>");
            } else {
                out.println("<msg>NotExist</msg>");
            }
            out.flush();
            out.close();
        } catch (Exception e) {

        }
    }

    @RequestMapping("/SaveInformation")
    public String SaveInformation(HttpServletRequest req, HttpServletResponse response) {
        String username = null;
        String password = null;
        String email = null;
        String lastname = null;
        String firstname = null;
        String status = null;
        String address1 = null;
        String address2 = null;
        String city = null;
        String state = null;
        String zip = null;
        String country = null;
        String phone = null;
        String languPr = null;
        String favoricate = null;
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (Exception e) {

        }

        username = req.getParameter("username");
        password = req.getParameter("password");
        password = EncryptUtil.md5(password);
        email = req.getParameter("email");
        lastname = req.getParameter("lastname");
        firstname = req.getParameter("firstname");
        status = req.getParameter("status");
        address1 = req.getParameter("address1");
        address2 = req.getParameter("address2");
        city = req.getParameter("city");
        state = req.getParameter("state");
        zip = req.getParameter("zip");
        country = req.getParameter("country");
        phone = req.getParameter("phone");
        languPr = req.getParameter("languagePreference");
        favoricate = req.getParameter("favouriteCategoryId");
        String listOption = req.getParameter("listOption");
        String bannerOption = req.getParameter("bannerOption");

        Account account = new Account();
        account.setUsername(username);
        account.setPassword(password);
        account.setPhone(phone);
        account.setCountry(country);
        account.setState(state);
        account.setCity(city);
        account.setAddress1(address1);
        account.setAddress2(address2);
        account.setStatus(status);
        account.setFirstName(firstname);
        account.setLastName(lastname);
        account.setLanguagePreference(languPr);
        account.setZip(zip);
        account.setFavouriteCategoryId(favoricate);
        account.setEmail(email);
        account.setListOption(Boolean.parseBoolean(listOption));
        account.setBannerOption(Boolean.parseBoolean(bannerOption));
        accountService.insertAccount(account);
        if (account != null) {
            String logInfo = logService.logInfo(" ") + " 注册新账号";
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        return "/account/SignonForm";
    }

    @RequestMapping("/UpdateInformation")
    public String UpdateInformation(HttpServletRequest req, HttpServletResponse response) {
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (Exception e) {

        }
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        String username = account.getUsername();
        String password = req.getParameter("password");
        password = EncryptUtil.md5(password);
        String firstName = req.getParameter("firstname");
        String lastName = req.getParameter("lastname");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address1 = req.getParameter("address1");
        String address2 = req.getParameter("address2");
        String city = req.getParameter("city");
        String state = req.getParameter("state");
        String zip = req.getParameter("zip");
        String country = req.getParameter("country");
        String languagePreference = req.getParameter("languagePreference");
        String favouriteCategoryId = req.getParameter("favouriteCategoryId");
        String listOption = req.getParameter("listOption");
        String bannerOption = req.getParameter("bannerOption");

        account.setUsername(username);
        account.setPassword(password);
        account.setFirstName(firstName);
        account.setLastName(lastName);
        account.setEmail(email);
        account.setPhone(phone);
        account.setAddress1(address1);
        account.setAddress2(address2);
        account.setCity(city);
        account.setState(state);
        account.setZip(zip);
        account.setCountry(country);
        account.setLanguagePreference(languagePreference);
        account.setFavouriteCategoryId(favouriteCategoryId);
        account.setListOption(Boolean.parseBoolean(listOption));
        account.setBannerOption(Boolean.parseBoolean(bannerOption));
        accountService.updateAccount(account);
        session.setAttribute("account", account);
        if (account != null) {
            String logInfo = logService.logInfo(" ") + " 账号信息更改";
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        return "/account/SignonForm";
    }

    @RequestMapping("/insertWish")
    public String insertWish(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        if(account==null){
            return "/account/SignonForm";
        }
        String wishItem = request.getParameter("Itemid");
        Wish wish = new Wish();
        wish.setUsername(account.getUsername());
        wish.setWishItem(wishItem);
        List<Wish> wishList1 = accountService.selectWish(account.getUsername());
        boolean flag = true;
        for(int i=0;i<wishList1.size();i++){
            if(wishList1.get(i).getWishItem().equals(wishItem)){
                flag = false;
            break;}
        }
        if(flag)
        accountService.insertWish(wish);
        List<Wish> wishList = accountService.selectWish(account.getUsername());
        List<Item> list = new ArrayList<>();
        for(int i=0;i<wishList.size();i++) {
            Item item = categortService.getItem(wishList.get(i).getWishItem());
            item.setDescription(categortService.getProduct(item.getItemId()).getDescn());
            list.add(item);
        }
        model.addAttribute("list",list);
        return "/account/wishlist";
    }
    @RequestMapping("/deleteWish")
    public String deleteWish(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        if(account==null){
            return "/account/SignonForm";
        }
        String wishItem = request.getParameter("Itemid");
        Wish wish = new Wish();
        wish.setUsername(account.getUsername());
        wish.setWishItem(wishItem);
        accountService.deleteWish(wish);
        List<Wish> wishList = accountService.selectWish(account.getUsername());
        List<Item> list = new ArrayList<>();
        for(int i=0;i<wishList.size();i++) {
            Item item = categortService.getItem(wishList.get(i).getWishItem());
            item.setDescription(categortService.getProduct(item.getItemId()).getDescn());
            list.add(item);
        }
        model.addAttribute("list",list);
        return "/account/wishlist";
    }
    @RequestMapping("/viewWishList")
    public String viewWishList(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        if(account==null){
            return "/account/SignonForm";
        }
        List<Wish> wishList = accountService.selectWish(account.getUsername());
        List<Item> list = new ArrayList<>();
        for(int i=0;i<wishList.size();i++) {
            Item item = categortService.getItem(wishList.get(i).getWishItem());
            item.setDescription(categortService.getProduct(item.getItemId()).getDescn());
            list.add(item);
        }
        model.addAttribute("list",list);
        return "/account/wishlist";
    }
}

